package com.example.makerspace.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.makerspace.config.SendMessageConfig;
import com.example.makerspace.dao.*;
import com.example.makerspace.domain.*;
import com.example.makerspace.dto.*;
import com.example.makerspace.enums.ResultCodeEnum;
import com.example.makerspace.service.ProxyModuleService;
import com.example.makerspace.utils.*;
import com.example.makerspace.vo.DataVO12;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProxyModuleServiceImpI implements ProxyModuleService {
    private final static String DEMAND_PICTURE_PATH_PREFIX = "demand/";

    @Resource
    private AgenciesDAO agenciesDAO;


    @Resource
    private SmsErrLogDAO smsErrLogDAO;

    @Resource
    private EnterpriseCertificationDAO enterpriseCertificationDAO;

    @Resource
    private AgencyProductRelationshipsDAO agencyProductRelationshipsDAO;

    @Resource
    private UserDAO userDAO;

    @Resource
    private DemandDAO demandDAO;

    @Resource
    private StagingProductDAO stagingProductDAO;

    @Resource
    private MessageDAO messageDAO;


    @Resource
    private SendMessageConfig sendMessageConfig;

    @Resource
    private  DeleteDemandDAO deleteDemandDAO;


  private  final  static  String   testHttpPrefix="https://119.45.199.13:3035/static/";

   private  final  static  String  devHttpPrefix="https://nism.ytcata.com:443/static/";


    @Override
    public Result getProxyFirm(HttpServletRequest request) {
        String username = JwtUtils.getUsername(request);
        List<AgencyProductRelationshipsDO> agencyProductRelationshipsDOS = agencyProductRelationshipsDAO.selectByUserName(username);
        List<AgencyProductRelationshipsDO> agencyProductRelationshipsDOList = agencyProductRelationshipsDOS.stream().filter(item -> item.getState().equals("可代理")).collect(Collectors.toList());
        List<String> collect1 = agencyProductRelationshipsDOList.stream().map(item -> item.getEntName()).collect(Collectors.toList());
        List<Integer> collect = agencyProductRelationshipsDOList.stream().map(item -> item.getId()).collect(Collectors.toList());
        ArrayList<DataVO12> dataVO12s = new ArrayList<>();
        for(int i=0;i<collect.size();i++){
            DataVO12 dataVO12 = new DataVO12(collect.get(i),collect1.get(i));
            dataVO12s.add(dataVO12);

        }
        return Result.success(dataVO12s);
    }

    @Override
    public Result getProxyProduct(PageRequest pageRequest) {
        Map<String, Object> params = pageRequest.getParams();
        String state = MapUtils.getString(params, "state");
            if (!state.equals("")) {
                IPage<AgencyProductRelationshipsDO> agencyProductRelationshipsDOIPage = agencyProductRelationshipsDAO.selectByPageCategory(pageRequest.getPagination(), state,pageRequest.getUsername());
                return Result.success(agencyProductRelationshipsDOIPage);
            }
            IPage<AgencyProductRelationshipsDO> agencyProductRelationshipsDOIPage = agencyProductRelationshipsDAO.selectByPageName(pageRequest.getPagination(), pageRequest.getUsername());
        return Result.success(agencyProductRelationshipsDOIPage);
        }

    @Override
    public Result updateProxy(Integer id, String op) {
            //代理审核中
        if (op.equals("1")) {
            AgencyProductRelationshipsDO agencyProductRelationshipsDO = agencyProductRelationshipsDAO.selectById(id);
            agencyProductRelationshipsDO.setState("审核中");
            agencyProductRelationshipsDAO.updateById(agencyProductRelationshipsDO);
            Result.success("修改状态成功!");
        } else if (op.equals("2")) {
            //代理通过
            AgencyProductRelationshipsDO agencyProductRelationshipsDO = agencyProductRelationshipsDAO.selectById(id);
            agencyProductRelationshipsDO.setState("已代理");
            agencyProductRelationshipsDAO.updateById(agencyProductRelationshipsDO);
            Result.success("修改状态成功!");
        }
        return Result.success();
    }

    @Override
    public Result addListProducts(List<DemandDTO> demandDTOList) {
        for (int i = 0; i < demandDTOList.size(); i++) {
            ArrayList<String> imagePaths = new ArrayList<>();
            ArrayList<String> outcomeInformation = new ArrayList<>();
            ArrayList<String> attachments = new ArrayList<>();
            DemandDO demandDO = new DemandDO();
            BeanUtils.copyProperties(demandDTOList.get(i), demandDO);
            UserDO userDO = userDAO.selectByUsername(demandDTOList.get(i).getUsername());
            if (userDO != null) {
                if (userDO.getIsAuthentication() == 0) {
                    continue;
                }
            }
            DemandDO oldDemandName = demandDAO.selectByDemandName(demandDTOList.get(i).getDemandName());
            DemandDO oldDemandContent = demandDAO.selectByContent(demandDTOList.get(i).getProductOverview());
            if (oldDemandName != null && oldDemandContent != null) {
                continue;
            }
            if (demandDTOList.get(i).getPicture() != null) {
                for (int j = 0; j < demandDTOList.get(i).getPicture().size(); j++) {
                    String image = ValidateCodeUtils.generateCode(4);
                    if (!ObjectUtils.isEmpty(demandDTOList.get(i).getPicture())) {
                        String imagePath = FileUtils.saveMultipartFile2(demandDTOList.get(i).getPicture().get(i), devHttpPrefix+ DEMAND_PICTURE_PATH_PREFIX + image,
                                FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + image);
                        imagePaths.add(imagePath);
                    }
                    demandDO.setPicture(imagePaths);
                }
            }
            if (demandDTOList.get(i).getAttachment() != null) {
                for (int k = 0; k < demandDTOList.get(i).getAttachment().size(); k++) {
                    String attachment = ValidateCodeUtils.generateCode(4);
                    if (!ObjectUtils.isEmpty(demandDTOList.get(i).getAttachment())) {
                        String imagePath = FileUtils.saveMultipartFile2(demandDTOList.get(i).getAttachment().get(i), devHttpPrefix+ DEMAND_PICTURE_PATH_PREFIX + attachment,
                                FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + attachment);
                        attachments.add(imagePath);
                    }
                    demandDO.setAttachment(attachments);
                }
            }
            if (demandDTOList.get(i).getOutcomeInformation() != null) {
                for (int z = 0; z < demandDTOList.get(i).getOutcomeInformation().size(); z++) {
                    String fileName = ValidateCodeUtils.generateCode(4);
                    if (!ObjectUtils.isEmpty(demandDTOList.get(i).getOutcomeInformation())) {
                        String imagePath = FileUtils.saveMultipartFile2(demandDTOList.get(i).getOutcomeInformation().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + fileName,
                                FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + fileName);
                        outcomeInformation.add(imagePath);
                    }
                    demandDO.setOutcomeInformation(outcomeInformation);
                }
            }
            String videsName = ValidateCodeUtils.generateCode(4);
            if (!ObjectUtils.isEmpty(demandDTOList.get(i).getProductVideos())) {
                String imagePath = FileUtils.saveMultipartFile2(demandDTOList.get(i).getProductVideos(), devHttpPrefix+ DEMAND_PICTURE_PATH_PREFIX + videsName,
                        FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + videsName);
                demandDO.setProductVideos(imagePath);
            }
            demandDO.setIsShow(0);
            List<EnterpriseCertificationDO> enterpriseCertificationDOS = enterpriseCertificationDAO.selectByPhoneNumber(demandDTOList.get(i).getUsername());
            if (!CollectionUtils.isEmpty(enterpriseCertificationDOS)) {
                demandDO.setCompanyName(enterpriseCertificationDOS.get(0).getEntName());
                demandDO.setCompanyAddress(enterpriseCertificationDOS.get(0).getMapAddress());

            }
            ArrayList<String> init = new ArrayList<>();
            demandDO.setPraiseUser(init);
            demandDO.setCollectionUser(init);
            demandDO.setShareUser(init);
            demandDO.setIsProxy(1);
            demandDAO.insert(demandDO);
            MessageDO messageDO = new MessageDO();
            messageDO.setType(1);
            messageDO.setUsername(demandDTOList.get(i).getUsername());
            messageDO.setTitle("上架产品消息");
            messageDO.setContent("您好!您的" + demandDTOList.get(i).getDemandName() + "产品上架成功,请等待审核!");
            messageDAO.insert(messageDO);
            try {
                MessageUtils.sendMessage(demandDTOList.get(i).getUsername(), sendMessageConfig.getShelvesProducts());
            } catch (Exception e) {
                SmsErrLogDO smsErrLogDO = new SmsErrLogDO();
                smsErrLogDO.setPhone(demandDTOList.get(i).getUsername());
                smsErrLogDO.setType("产品上架审核");
                smsErrLogDAO.insert(smsErrLogDO);
            }
            ;
        }
        return Result.success();
    }

    @Override
    public Result contactFirm(String entName) {
        List<EnterpriseCertificationDO> enterpriseCertificationDOS = enterpriseCertificationDAO.selectByEntName(entName);
        return Result.success(enterpriseCertificationDOS.get(0));
    }

    @Override
    public Result stageProduct(StagingProductDTO stagingProductDTO) {
        ArrayList<String> imagePaths = new ArrayList<>();
        ArrayList<String> outcomeInformation = new ArrayList<>();
        ArrayList<String> attachments = new ArrayList<>();
        StagingProductDO stagingProductDO = new StagingProductDO();
        if (stagingProductDTO.getDemandName() == null) {
            return Result.error(ResultCodeEnum.Other_Error);
        }
        BeanUtils.copyProperties(stagingProductDTO, stagingProductDO);

        if (stagingProductDTO.getPicture() != null) {
            for (int i = 0; i < stagingProductDTO.getPicture().size(); i++) {
                String image = ValidateCodeUtils.generateCode(4);
                if (!ObjectUtils.isEmpty(stagingProductDTO.getPicture())) {
                    String imagePath = FileUtils.saveMultipartFile2(stagingProductDTO.getPicture().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + image,
                            FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + image);
                    imagePaths.add(imagePath);
                }
                stagingProductDO.setPicture(imagePaths);
            }
        }
        if (stagingProductDTO.getAttachment() != null) {
            for (int i = 0; i < stagingProductDTO.getAttachment().size(); i++) {
                String attachment = ValidateCodeUtils.generateCode(4);
                if (!ObjectUtils.isEmpty(stagingProductDTO.getAttachment())) {
                    String imagePath = FileUtils.saveMultipartFile2(stagingProductDTO.getAttachment().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + attachment,
                            FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + attachment);
                    attachments.add(imagePath);
                }
                stagingProductDO.setAttachment(attachments);
            }
        }
        if (stagingProductDTO.getOutcomeInformation() != null) {
            for (int i = 0; i < stagingProductDTO.getOutcomeInformation().size(); i++) {
                String fileName = ValidateCodeUtils.generateCode(4);
                if (!ObjectUtils.isEmpty(stagingProductDTO.getOutcomeInformation())) {
                    String imagePath = FileUtils.saveMultipartFile2(stagingProductDTO.getOutcomeInformation().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + fileName,
                            FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + fileName);
                    outcomeInformation.add(imagePath);
                }
                stagingProductDO.setOutcomeInformation(outcomeInformation);
            }
        }
        String videsName = ValidateCodeUtils.generateCode(4);
        if (!ObjectUtils.isEmpty(stagingProductDTO.getProductVideos())) {
            String imagePath = FileUtils.saveMultipartFile2(stagingProductDTO.getProductVideos(), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + videsName,
                    FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + videsName);
            stagingProductDO.setProductVideos(imagePath);
        }
        List<StagingProductDO> stagingProductDOS = stagingProductDAO.selectByDemandName(stagingProductDTO.getDemandName());
        if (CollectionUtils.isEmpty(stagingProductDOS)) {
            stagingProductDAO.insert(stagingProductDO);
            return Result.success("自动保存成功!");
        } else {
            stagingProductDAO.updateById(stagingProductDOS.get(0));
            return Result.success("自动保存成功!");
        }
    }

    @Override
    public Result getStageProduct(HttpServletRequest request) {
        String username = JwtUtils.getUsername(request);
        List<StagingProductDO> stagingProductDOS = stagingProductDAO.selectByUserName(username);
        return Result.success(stagingProductDOS);
    }

    @Override
    public Result userAgent(DemandDTO demandDTO) {
        List<AgencyProductRelationshipsDO> agencyProductRelationshipsDOS = agencyProductRelationshipsDAO.selectByUsernameAndEntName(demandDTO.getUsername(), demandDTO.getEntName());
        if (CollectionUtils.isEmpty(agencyProductRelationshipsDOS)) {
            return Result.error(ResultCodeEnum.PROXY_AUDIT);
        } else if (agencyProductRelationshipsDOS.get(0).getState().equals("审核中")) {
            return Result.error(ResultCodeEnum.PROXY_AUDIT);
        } else if (agencyProductRelationshipsDOS.get(0).getState().equals("可代理")) {
            AgencyProductRelationshipsDO agencyProductRelationshipsDO = agencyProductRelationshipsDAO.selectById(demandDTO.getProxyId());
            ArrayList<String> imagePaths = new ArrayList<>();
            ArrayList<String> outcomeInformation = new ArrayList<>();
            ArrayList<String> attachments = new ArrayList<>();
            DemandDO demandDO = new DemandDO();
            BeanUtils.copyProperties(demandDTO, demandDO);
            UserDO userDO = userDAO.selectByUsername(demandDTO.getUsername());
            if (userDO != null) {
                if (userDO.getIsAuthentication() == 0) {
                    return Result.error(ResultCodeEnum.Unable_Finally_Authentication);
                }
            }
            DemandDO oldDemandName = demandDAO.selectByDemandName(demandDTO.getDemandName());
            DemandDO oldDemandContent = demandDAO.selectByContent(demandDTO.getProductOverview());
            if (oldDemandName != null && oldDemandContent != null) {
                return Result.error(ResultCodeEnum.Product_EXIST);
            }
            if (demandDTO.getPicture() != null) {
                for (int i = 0; i < demandDTO.getPicture().size(); i++) {
                    String image = ValidateCodeUtils.generateCode(4);
                    if (!ObjectUtils.isEmpty(demandDTO.getPicture())) {
                        String imagePath = FileUtils.saveMultipartFile2(demandDTO.getPicture().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + image,
                                FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + image);
                        imagePaths.add(imagePath);
                    }
                    demandDO.setPicture(imagePaths);
                }
            }
            if (demandDTO.getAttachment() != null) {
                for (int i = 0; i < demandDTO.getAttachment().size(); i++) {
                    String attachment = ValidateCodeUtils.generateCode(4);
                    if (!ObjectUtils.isEmpty(demandDTO.getAttachment())) {
                        String imagePath = FileUtils.saveMultipartFile2(demandDTO.getAttachment().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + attachment,
                                FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + attachment);
                        attachments.add(imagePath);
                    }
                    demandDO.setAttachment(attachments);
                }
            }
            if (demandDTO.getOutcomeInformation() != null) {
                for (int i = 0; i < demandDTO.getOutcomeInformation().size(); i++) {
                    String fileName = ValidateCodeUtils.generateCode(4);
                    if (!ObjectUtils.isEmpty(demandDTO.getOutcomeInformation())) {
                        String imagePath = FileUtils.saveMultipartFile2(demandDTO.getOutcomeInformation().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + fileName,
                                FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + fileName);
                        outcomeInformation.add(imagePath);
                    }
                    demandDO.setOutcomeInformation(outcomeInformation);
                }
            }
            String videsName = ValidateCodeUtils.generateCode(4);
            if (!ObjectUtils.isEmpty(demandDTO.getProductVideos())) {
                String imagePath = FileUtils.saveMultipartFile2(demandDTO.getProductVideos(), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + videsName,
                        FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + videsName);
                demandDO.setProductVideos(imagePath);
            }
            demandDO.setIsShow(0);
            List<EnterpriseCertificationDO> enterpriseCertificationDOS = enterpriseCertificationDAO.selectByPhoneNumber(demandDTO.getUsername());
            if (!CollectionUtils.isEmpty(enterpriseCertificationDOS)) {
                demandDO.setCompanyName(enterpriseCertificationDOS.get(0).getEntName());
                demandDO.setCompanyAddress(enterpriseCertificationDOS.get(0).getMapAddress());

            }
            ArrayList<String> init = new ArrayList<>();
            demandDO.setIsProxy(1);
            demandDO.setPraiseUser(init);
            demandDO.setCollectionUser(init);
            demandDO.setShareUser(init);
            List<DemandDO> demandDOS = demandDAO.selectAll();
            List<DeleteDemandDO> deleteDemandDOS = deleteDemandDAO.selectAll();
            List<DemandDO> collect = demandDOS.stream().filter(item -> item.getCategory().equals(demandDTO.getCategory())).collect(Collectors.toList());
            List<DeleteDemandDO> collect1 = deleteDemandDOS.stream().filter(item -> item.getCategory().equals(demandDTO.getCategory())).collect(Collectors.toList());
            String serialNumber = makeSerialNumber(demandDTO.getCategory(),collect.size()+collect1.size());
            demandDO.setSerialNumber(serialNumber);
            demandDAO.insert(demandDO);
            agencyProductRelationshipsDO.setProductName(demandDTO.getDemandName());
            DemandDO demandDO1 = demandDAO.selectByDemandName(demandDTO.getDemandName());
            if(demandDO1!=null){
                agencyProductRelationshipsDO.setProductId(demandDO1.getId());
            }
            agencyProductRelationshipsDO.setProductState("审核中");
            agencyProductRelationshipsDO.setProductIntroduction(demandDTO.getProductOverview());
            agencyProductRelationshipsDAO.updateById(agencyProductRelationshipsDO);
            List<StagingProductDO> stagingProductDOS = stagingProductDAO.selectByDemandName(demandDTO.getDemandName());
            if (!CollectionUtils.isEmpty(stagingProductDOS)) {
                for (StagingProductDO stagingProductDO : stagingProductDOS) {
                    stagingProductDAO.deleteById(stagingProductDO.getId());
                }
            }
            MessageDO messageDO = new MessageDO();
            messageDO.setType(1);
            messageDO.setUsername(demandDTO.getUsername());
            messageDO.setTitle("上架产品消息");
            messageDO.setContent("您好!您的" + demandDTO.getDemandName() + "产品上架成功,请等待审核!");
            messageDAO.insert(messageDO);
            MessageUtils.sendMessage(demandDTO.getUsername(), sendMessageConfig.getShelvesProducts());
            return Result.success();
        }
        return  Result.success();
    }
    public  String  makeSerialNumber(String category,Integer size){
        String sid = ValidateCodeUtils.fillString(size, 3);
        String serialNumber="";
        if(category.equals("人工智能")){
            serialNumber="RG";
        }
        else  if(category.equals("机器人")){
            serialNumber="JQR";
        }
        else if(category.equals("大数据")){
            serialNumber="SJ";
        }
        else if(category.equals("智能设备")){
            serialNumber="ZN";
        }
        else if(category.equals("通信工程")){
            serialNumber="TX";
        }
        else if(category.equals("系统软件")){
            serialNumber="XT";
        }
        else if(category.equals("移动应用")){
            serialNumber="YD";
        }
        else if(category.equals("其他")){
            serialNumber="QT";
        }
        serialNumber=serialNumber+"-"+sid;

        return  serialNumber;
    }

    @Override
    public Result agentEntList(HttpServletRequest request){
        String username = JwtUtils.getUsername(request);
        List<AgencyProductRelationshipsDO> agencyProductRelationshipsDOS = agencyProductRelationshipsDAO.selectByUserName(username);
        return  Result.success(agencyProductRelationshipsDOS);
    }

    @Override
    public Result proxyAuthentication(AgencyProductRelationshipsDTO agencyProductRelationshipsDTO) {
        AgencyProductRelationshipsDO agencyProductRelationshipsDO = new AgencyProductRelationshipsDO();
        String entName = agencyProductRelationshipsDTO.getEntName();
        List<EnterpriseCertificationDO> enterpriseCertificationDOS = enterpriseCertificationDAO.selectByEntName(entName);
        if(!CollectionUtils.isEmpty(enterpriseCertificationDOS)){
            agencyProductRelationshipsDO.setAvatar(enterpriseCertificationDOS.get(0).getLogo());
            agencyProductRelationshipsDO.setEntName(enterpriseCertificationDOS.get(0).getEntName());
        }

        BeanUtils.copyProperties(agencyProductRelationshipsDTO,agencyProductRelationshipsDO);
        ArrayList<String> agentManuals = new ArrayList<>();
        if (agencyProductRelationshipsDTO.getAgentManual() != null) {
            for (int i = 0; i < agencyProductRelationshipsDTO.getAgentManual().size(); i++) {
                String attachment = ValidateCodeUtils.generateCode(4);
                if (!ObjectUtils.isEmpty(agencyProductRelationshipsDTO.getAgentManual())) {
                    String agentManual = FileUtils.saveMultipartFile2(agencyProductRelationshipsDTO.getAgentManual().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + attachment,
                            FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + attachment);
                    agentManuals.add(agentManual);
                }
                agencyProductRelationshipsDO.setAgentManual(agentManuals);
            }
        }
        agencyProductRelationshipsDO.setState("审核中");
        agencyProductRelationshipsDO.setProductState("");
        agencyProductRelationshipsDAO.insert(agencyProductRelationshipsDO);
        return Result.success();
    }

    @Override
    public Result showProductDetail(String productName) {
        DemandDO demandDO = demandDAO.selectByDemandName(productName);
        return  Result.success(demandDO);
    }

    @Override
    public Result cancelProxy(Integer id) {
        AgencyProductRelationshipsDO agencyProductRelationshipsDO = agencyProductRelationshipsDAO.selectById(id);
        String entName = agencyProductRelationshipsDO.getEntName();
        List<AgencyProductRelationshipsDO> agencyProductRelationshipsDOS = agencyProductRelationshipsDAO.selectByEntName(entName);
        for(int i=0;i<agencyProductRelationshipsDOS.size();i++){
            Integer productId = agencyProductRelationshipsDOS.get(i).getProductId();
            if(productId!=null){
                DemandDO demandDO = demandDAO.selectById(productId);
                if(demandDO.getIsShow().equals(0)||demandDO.getIsShow().equals(-1)){
                    demandDAO.deleteById(productId);
                }
            }
        }
        agencyProductRelationshipsDAO.deleteByEntName(entName);
          return  Result.success("取消代理成功");
    }
}
